package com.cxyzy.demo

import android.location.Location
import android.os.Bundle
import android.view.View.GONE
import android.view.View.VISIBLE
import androidx.appcompat.app.AppCompatActivity
import com.afollestad.assent.Permission
import com.afollestad.assent.runWithPermissions
import com.cxyzy.demo.Utils.getAddressInfo
import com.cxyzy.demo.Utils.showAlert
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        locateBtn.setOnClickListener { locate() }
    }

    private fun locate() {
        locationTv.text = ""
        runWithPermissions(Permission.ACCESS_FINE_LOCATION) {
            if (LocationUtils.isLocationProviderEnabled(this@MainActivity)) {
                progressBar.visibility = VISIBLE
                showLocationWithToast()
            } else {
                showAlert("本应用需要获取地理位置，请打开获取位置的开关", this)
            }
        }
    }

    private fun showLocationWithToast() {
        LocationUtils.getLocation(this@MainActivity, object : Callback {
            override fun onLocationChanged(location: Location) {
                onGetLocation(location)
            }
        })
    }

    private fun onGetLocation(location: Location) {
        GlobalScope.launch(Dispatchers.IO) {
            val result = getAddressInfo(location)
            launch(Dispatchers.Main) {
                result?.let {
                    locationTv.text = it.toString()
                    progressBar.visibility = GONE
                }
            }
        }
    }
}
